package com.kotodama.application.cqrs.bus;

import com.kotodama.application.cqrs.commands.Command;
import com.kotodama.application.cqrs.handlers.CommandHandler;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 命令总线，负责将命令分发到相应的处理器
 */
@Component
public class CommandBus {

    private final Map<Class<? extends Command>, CommandHandler<?, ?>> handlers = new HashMap<>();

    public CommandBus(List<CommandHandler<?, ?>> commandHandlers) {
        commandHandlers.forEach(handler -> handlers.put(handler.getSupportedCommandType(), handler));
    }

    /**
     * 执行命令
     * 
     * @param command 要执行的命令
     * @param <R>     返回结果类型
     * @return 执行结果
     */
    @SuppressWarnings("unchecked")
    public <R> R execute(Command command) {
        CommandHandler<Command, R> handler = (CommandHandler<Command, R>) handlers.get(command.getClass());

        if (handler == null) {
            throw new IllegalArgumentException("未找到命令处理器: " + command.getClass().getSimpleName());
        }

        return handler.handle(command);
    }
}